package com.tnl.web.controller;

import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.Domain;
import com.biz.hunter.db.entity.Hunter;
import com.biz.hunter.db.entity.HunterCompany;
import com.biz.hunter.db.entity.Person;
import com.tnl.web.config.controller.Authentication;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.service.HunterService;
import com.tnl.web.util.qualifiers.AuditIt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HunterController {

	private static final Logger logger = LoggerFactory.getLogger(HunterController.class);

	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private HunterDAO hunterDAO;
	@Autowired
	private HunterCompanyDAO hunterCompanyDAO;
	
	@Autowired
	private Authentication authentication;

	@Autowired
	private HunterService hunterService;
	
	// 猎头管理首页
	@AuditIt(module = "Hunter", action = "hunter_view", description = "show the hunter index page")
	@RequestMapping(value = "admin/hunter/manage.page", method = RequestMethod.GET)
	public String hunterManagement(HttpServletRequest request, Model model) {

		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {

			logger.info("empty user id ,session is not initiallized.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}
		
	//	List<HunterCompany> companies = hunterCompanyDAO.getALL();//	model.addAttribute("companies", companies);
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
		return "admin/hunter/hunterlist";
	}

	// 显示编辑表单页面
	@AuditIt(module = "Hunter", action = "editHunter", description = "show the hunter edit page")
	@RequestMapping(value = "admin/hunter/form.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, Model model) {

		String hunterId = request.getParameter("hunterid");
		Hunter hunter = null;
		if (StringUtils.hasText(hunterId)) {
			hunter = hunterDAO.getById(Integer.parseInt(hunterId));
			model.addAttribute("hunter", hunter);
		} else {
			return "admin/errorpage";
		}

		List<Domain> domains = domainDAO.getALL();
		model.addAttribute("domains", domains);
		List<HunterCompany> companies = hunterCompanyDAO.getALL();
		model.addAttribute("companies", companies);

		return "admin/hunter/huntereditform";
	}

	// 显示候选人详细信息页面
	@RequestMapping(value = "admin/hunter/detail.page", method = RequestMethod.GET)
	public String employeeDetail(HttpServletRequest request, Model model) {

		String hunterId = request.getParameter("hunterid");
		
		Hunter hunter = null;
		if (StringUtils.hasText(hunterId)) {
			hunter = hunterDAO.getById(Integer.parseInt(hunterId));
			model.addAttribute("hunter", hunter);
		} else {
			return "admin/errorpage";
		}
		
		int companyid = hunter.getCompanyId();
		HunterCompany hunterCompany = hunterCompanyDAO.getById(companyid);
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("company", hunterCompany);
		model.addAttribute("domains", domains);

		return "admin/hunter/hunterdetail";
	}
		
	// 公司认证
	@AuditIt(module = "Hunter", action = "approveCompany", description = "公司审核认证")
	@RequestMapping(value = "admin/hunter/approve.page", method = RequestMethod.GET)
	public @ResponseBody Map<String,Object> approveCompany(HttpServletRequest request, Model model) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		String hunterId = request.getParameter("hunterid");
		Hunter hunter = null;
		if (StringUtils.hasText(hunterId)) {
			hunter = hunterDAO.getById(Integer.parseInt(hunterId));
			model.addAttribute("hunter", hunter);
		} else {
			logger.debug("hunterId 为空");
			result.put("msg","id不存在");
		}

		hunterService.approve(Integer.parseInt(hunterId));
		result.put("msg","操作成功");
		return result;
//		int companyId = hunter.getCompanyId();
//		HunterCompany company = null;
//		if (companyId >0) {
//			company = hunterCompanyDAO.getById(companyId);
//			model.addAttribute("company", company);
//		}
//
//		List<HunterCompany> companies = hunterCompanyDAO.getALL();
//		model.addAttribute("companies", companies);
//
//		return "admin/hunter/companyapprove";
	}
		
	/*	
	@RequestMapping(value = "admin/hunter/toView.page", method = RequestMethod.GET)
	public String toView(HttpServletRequest request, int id, Model model) {
		Hunter hunter = hunterDAO.getById(id);
		model.addAttribute("hunter", hunter)	;
		return "admin/hunter/detail";
	}
	
	@RequestMapping(value = "admin/hunter/toEdit.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, int id, Model model) {
		Hunter hunter = hunterDAO.getById(id);
		model.addAttribute("hunter", hunter)	;
		return "admin/hunter/edit";
	}
	
	@RequestMapping(value = "admin/hunter/create.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg createHunter( Hunter hunter) {
		ErrorMsg msg = new ErrorMsg();
		if (hunter==null) {
			
			logger.error("the input parameter is null");
			msg.setMsg("hunter is null");
		}
		int result = hunterDAO.save(hunter);
		 if(result == -1 )
		    {
		    	msg.setErrorcode("50001");
				msg.setMsg("can not save the person" + hunter.getName());
				return msg;
		    }
			msg.setErrorcode("0");
			msg.setMsg("success");
			
			return msg;
	}
	*/

	//@RequestMapping(value = "admin/candidate/checkExist.do", method = RequestMethod.POST)
	private boolean isExist(Person person) {
		if (person == null) {
			return true;
		}

		if (StringUtils.hasText(person.getPhone())) {
			Person persondb = hunterDAO.getByPhone(person.getPhone());
			if (persondb == null) {
				return false;
			}
		}
		return true;
	}
	
	@RequestMapping(value = "admin/hunter/activate.do", method = RequestMethod.GET)
	public String activateHunter(HttpServletRequest request, int id, Model model) {
		
		return "admin/hunter/list";
	}
	
	@RequestMapping(value = "admin/hunter/inactivate.do", method = RequestMethod.GET)
	public String inactivateHunter(HttpServletRequest request, int id, Model model) {
		return "admin/hunter/list";
	}
	
	// 搜索数据
	@RequestMapping(value = "admin/hunter/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Hunter> searchHunter(jqGridRequestObject request,
			String sname, Integer scompanyid, String sphone) {
		
		jqGridResponseObject<Hunter> msg = new jqGridResponseObject<Hunter>();
		
		long page = request.getPage();
		long pagesize = request.getRows();
		
		long totalrows = request.getTotalrows();
		long totalpages = 0;
		
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = hunterDAO.getCountOfAll(sname, scompanyid,sphone);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
		
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;
		
		List<Hunter> list = hunterDAO.getAllWithLimit(sname, scompanyid,sphone,start, pagesize);
		
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
		
		return msg;
	}
	
	// 更新数据
	@AuditIt(module = "Hunter", action = "editHunter", description = "edit hunter action")
	@RequestMapping(value = "admin/hunter/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateHunter(HttpServletRequest request,  Hunter hunter) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if(hunter == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定猎头信息");
			return msg;
		}
		if(hunter.getId() <= 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定猎头信息");
			return msg;
		}
		
		Hunter ht = hunterDAO.getById(hunter.getId());
		if(ht == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该猎头");
			return msg;
		}
		
		ht.setName(hunter.getName());
		ht.setAge(hunter.getAge());
		ht.setBestdomain(hunter.getBestdomain());
		ht.setWorkage(hunter.getWorkage());
		ht.setTelephone(hunter.getTelephone());
		ht.setEmail(hunter.getEmail());
		ht.setPhone(hunter.getPhone());
		ht.setCompanyId(hunter.getCompanyId());
		
		int companyid = hunter.getCompanyId();
		HunterCompany cp = hunterCompanyDAO.getById(companyid);
		ht.setCompanyName(cp.getName());

		int result = hunterDAO.update(ht);
		if (result == -1) {
			msg.setErrorcode("5001");
			msg.setMsg("更新数据失败");
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("数据更新成功");
		return msg;
	}
	
	// 删除数据
	@AuditIt(module = "Hunter", action = "deleteHunter", description = "delete hunter action")
	@RequestMapping(value = "admin/hunter/delete.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg deleteHunter(HttpServletRequest request, Integer hunterid) {
		
		ErrorMsg msg = new ErrorMsg();
		
		if (hunterid == null) {
			logger.debug("empid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}
		
		int result = hunterDAO.delete(String.valueOf(hunterid));
		if (result == 1) {
			msg.setErrorcode("0");
			msg.setMsg("删除成功");
			return msg;
		}

		msg.setErrorcode("50001");
		msg.setMsg("删除失败");
		return msg;
	}

	@ResponseBody
	@RequestMapping(value = "admin/hunter/approve.do", method = RequestMethod.POST)
	public ErrorMsg normaliseCompany(HttpServletRequest request, HunterCompany company) {
		
		ErrorMsg msg = new ErrorMsg();
		
		Hunter ht = null;
		
		String hunterId = request.getParameter("hunterid");
		if (StringUtils.hasText(hunterId)) {
			ht = hunterDAO.getById(Integer.parseInt(hunterId));
		} else {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定猎头信息");
			return msg;
		}
		
		if(ht == null) {
			msg.setErrorcode("500101");
			msg.setMsg("猎头不存在");
			return msg;
		}
		
		String op = request.getParameter("op");
		if (!StringUtils.hasText(op)) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定操作");
			return msg;
		}
		
		if(!(op.compareToIgnoreCase("create")== 0 || op.compareToIgnoreCase("subsitute")== 0)) {
			msg.setErrorcode("500101");
			msg.setMsg("指定操作不对");
			return msg;
		}
		
		if(company == null) {
			msg.setErrorcode("500101");
			msg.setMsg("提交的数据不对");
			return msg;
		}
		
		if(!StringUtils.hasText(company.getName())) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司名");
			return msg;
		}
		
		HunterCompany cp = null;
		if(op.compareToIgnoreCase("subsitute")== 0) {
			cp = hunterCompanyDAO.getByName(company.getName());
			if(cp == null) {
				msg.setErrorcode("500101");
				msg.setMsg("你选择的公司名并非标准化公司名，请重新尝试");
				return msg;
			}
			// 如果已经是标准化公司名，那么进行替换
			ht.setCompanyId(cp.getId());
			ht.setCompanyName(cp.getName());
			ht.setBinded(1);

			int ret = hunterDAO.update(ht); 
			if(ret != -1) {
				msg.setErrorcode("0");
				msg.setMsg("使用已有公司成功");
				return msg;
			}
		}
		
		// TODO:这里的逻辑有可能会乱套，需要花时间仔细思考一下具体的逻辑
		if(op.compareToIgnoreCase("create")== 0) {
			cp = hunterCompanyDAO.getByName(company.getName());
			// 如果该公司名存在，那么就是
			if(cp != null) {
				msg.setErrorcode("500101");
				msg.setMsg("该公司已存在，请重新尝试approve.page");
				return msg;
			}
			
			// 如果该公司名不存在，那么就认为是更新公司信息
			cp = hunterCompanyDAO.getById(ht.getCompanyId());
			if(cp == null) {
				msg.setErrorcode("500101");
				msg.setMsg("该公司不存在，请重新尝试");
				return msg;
			}
			cp.setApproved(1);
			cp.setName(company.getName());
			cp.setAddress(company.getAddress());
			cp.setContact(company.getContact());
			cp.setPhone(company.getPhone());
			cp.setLicenseCode(company.getLicenseCode());
			cp.setOrgnizationCode(company.getOrgnizationCode());
			
			int companyid = hunterCompanyDAO.update(cp);
			if(companyid == -1) {
				msg.setErrorcode("500101");
				msg.setMsg("更新公司数据失败，请重新尝试");
				return msg;
			}
			ht.setBinded(1);
			ht.setCompanyName(company.getName());
			int ret = hunterDAO.update(ht); 
			if(ret == -1) {
				msg.setErrorcode("500101");
				msg.setMsg("操作失败");
				return msg;
			}
		}
		
		msg.setErrorcode("0");
		msg.setMsg("操作成功");

		return msg;
	}

}
